package com.cndw.kungfu.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.cndw.kungfu.comm.tencent.LogFieldType;
import com.cndw.kungfu.comm.tencent.QQDC;
import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsConfig;
import com.cndw.kungfu.config.ConstantsCost;
import com.cndw.kungfu.config.ConstantsDailyItem;
import com.cndw.kungfu.config.ConstantsDayIntKey;
import com.cndw.kungfu.config.ConstantsIntKey;
import com.cndw.kungfu.config.ConstantsLevel;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.config.ConstantsModel;
import com.cndw.kungfu.config.ConstantsTask;
import com.cndw.kungfu.config.GoodsEffectConfig;
import com.cndw.kungfu.domain.Goods;
import com.cndw.kungfu.domain.GoodsMode;
import com.cndw.kungfu.domain.LevelUpgrade;
import com.cndw.kungfu.domain.Pet;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.domain.SkillMode;
import com.cndw.kungfu.ext.LangUtil;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.NumberProcesser;
import com.cndw.kungfu.ext.StringProcesser;
import com.cndw.kungfu.ext.WordProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.goods.PlayerBoxs;
import com.cndw.kungfu.model.pet.domain.PetSoul;
import com.cndw.kungfu.model.pet.domain.PetSoulOrder;
import com.cndw.kungfu.model.pet.domain.Soul;
import com.cndw.kungfu.model.sys.ChatMain;
import com.cndw.kungfu.model.sys.LogServer;
import com.cndw.kungfu.vo.PetSoulVO;
import com.cndw.kungfu.vo.PetVO;
import com.cndw.rpg.annotation.Controller;
import com.cndw.rpg.framework.ResponseMessage;
import com.cndw.rpg.framework.Session;

/**
 * 宠物的执行
 * 
 * @author fantadust [9677889@qq.com]
 * @date 2012-2-21 下午7:41:30
 */
@Controller
public class PetController {

	/**
	 * 显示宠物
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage show(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());

		Map<Long, Pet> petsMap = player.getDataInfo().getPetsMap();
		if (petsMap.isEmpty()) {
			return ResponseMessage.getFailMessage(false);
		}
		List<PetVO> pets = new ArrayList<PetVO>();
		for (Pet e : petsMap.values()) {
			pets.add(e.toVO());
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pets", pets);
		map.put("petId", player.getDataInfo().getPetId());
		map.put("petPreGold", ConstantsModel.petPreGold);
		map.put("petPreAdd", ConstantsModel.petPreAdd);
		map.put("petSpiritAdd", ConstantsModel.petSpiritAdd);
		map.put("autoBag", player.getDataInfo().intDataGet(ConstantsIntKey.aPetBag));
		//map.put("pff", player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.pff));
		QQDC.getInstance().logClick(player, LogFieldType.pet);

		return ResponseMessage.getSuccMessage(map);

	}

	public ResponseMessage showOther(Session session, long playerId) {
		Player target = Context.getPlayerServer().getByPlayerId(playerId);
		if (target == null) {
			return null;
		}
		Pet pet = target.getDataInfo().getPet();
		if (pet == null) {
			return ResponseMessage.getSuccMessage(false);
		}

		return ResponseMessage.getSuccMessage(pet.toVO());
	}

	/**
	 * 宠物放生
	 * 
	 * @param session
	 * @param id
	 * @return
	 */
	public ResponseMessage giveUp(Session session, long id) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getDataInfo().isGoodsLock()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("player.pass.lockctrl"));
		}
		Map<Long, Pet> petsMap = player.getDataInfo().getPetsMap();
		if (petsMap.size() == 1) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pet.give.one"));
		}
		if (!petsMap.containsKey(id)) {
			return ResponseMessage.getFailMessage(false);
		}
		if (id == player.getDataInfo().getPetId()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pet.give.onbattle"));
		}
		Pet pet = petsMap.get(id);
		pet.setPlayerId(0);
		pet.commitSync();
		petsMap.remove(id);
		if (id == player.getDataInfo().getPetId()) {
			player.getDataInfo().setPetId(0);
		}

		LogServer.recordLog(player, ConstantsLog.player, 30011, pet.getName(), pet.getId(), pet.getMode().getName(), pet.getLevel(), pet.getGrowth(),
				pet.getStar());

		return ResponseMessage.getSuccMessage(true);
	}

	/**
	 * 出战状态
	 * 
	 * @param session
	 * @param id
	 * @return
	 */
	public ResponseMessage status(Session session, long id) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Map<Long, Pet> petsMap = player.getDataInfo().getPetsMap();
		if (id > 0 && petsMap.containsKey(id)) {
			player.getDataInfo().setPetId(id);

			Context.getTaskServer().notifyToSpark(session.getUid(), ConstantsTask.spark35Pet, 1);
			Pet pet = player.getDataInfo().getPet(id);
			LogServer.recordLog(player, ConstantsLog.player, 30032,pet.getName(),pet.getMode().getName(),pet.getId());
		} else {
			player.getDataInfo().setPetId(0);
			LogServer.recordLog(player, ConstantsLog.player, 30032,id);
		}
		player.getDataInfo().commitSync();
		Context.getPlayerServer().clacScore(player);		
		
		
		return ResponseMessage.getSuccMessage(player.getDataInfo().getPetId());
	}

	/**
	 * 改名字
	 * 
	 * @param session
	 * @param id
	 * @param name
	 * @return
	 */
	public ResponseMessage rename(Session session, long id, String name) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Pet pet = player.getDataInfo().getPet(id);
		if (pet == null) {
			return null;
		}
		int nameLength = name.getBytes(Constants.charset).length;
		if (nameLength < 4 || nameLength > 15) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pet.name.length", 4, 15));
		} else if (!WordProcesser.chkPerg(name, ConstantsConfig.getCommCreateNameExp())) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pet.name.err"));
		} else if (WordProcesser.chkBadWorlds(name) != null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pet.name.err"));
		}

		pet.setName(name);
		pet.commitSync();

		return ResponseMessage.getSuccMessage(pet.getName());
	}

	/**
	 * 自动使用气血包
	 * 
	 * @param session
	 * @param isOk
	 * @return
	 */
	public ResponseMessage autoBag(Session session, boolean isOk) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());

		if (isOk) {
			player.getDataInfo().intDataSet(ConstantsIntKey.aPetBag, 1);
		} else {
			player.getDataInfo().intDataRemove(ConstantsIntKey.aPetBag);
		}
		player.getDataInfo().commitSync();

		return ResponseMessage.getSuccMessage(isOk);
	}

	/**
	 * 喂养宠物
	 * 
	 * @param session
	 * @param id
	 * @param goodsId
	 * @param equipIds
	 * @return
	 */
	public ResponseMessage feed(Session session, long id, int goodsId, String equipIds, int idsType) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Pet pet = player.getDataInfo().getPet(id);
		if (pet == null) {
			return null;
		} else if (pet.getLevel() >= player.getLevel()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pet.feed.level"));
		}
		String goodsName = null;
		int equipNum = 0;
		int alter = 0;
		StringBuilder sb = new StringBuilder();
		HashMap<String, Integer> goodsMap = new HashMap<String, Integer>();
		if (goodsId > 0) {
			GoodsMode goodsMode = Context.getGoodsServer().getModeById(goodsId);
			if (goodsMode.getAppId() != 111) {// 不是饲养丹
				return null;
			}
			if (!player.getPlayerBoxs().isHaveGoods(goodsId)) {
				return null;
			}
			goodsName = goodsMode.getName();
			player.getPlayerBoxs().costGoods(goodsId, 1);
			alter = goodsMode.getValueB();

		} else if (equipIds != null && equipIds.length() > 0) {
			if (player.getDataInfo().isGoodsLock()) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("player.pass.lockctrl"));
			}
			int[] equipIdList = StringProcesser.toIntArray(equipIds);
			if (equipIdList != null) {
				PlayerBoxs playerBoxs = player.getPlayerBoxs();

				for (int i : equipIdList) {
					Goods goods = playerBoxs.get(i);
					if (goods == null || goods.getGoodsMode() == null) {
						continue;
					}
					if (idsType == 1 && !goods.getGoodsMode().isEquiq()) {
						continue;
					} else if (idsType == 2 && goods.getGoodsMode().getAppId() != 110) {// 110=宠物蛋
						continue;
					}else if (goods.getGoodsMode().getNpcRecover() == 0) {
						continue;
					}

					int coff = idsType == 1 ? 1000 : 10 * goods.getStackNum();
					if (goodsMap.containsKey(goods.getGoodsMode().getName())) {
						goodsMap.put(goods.getGoodsMode().getName(), goodsMap.get(goods.getGoodsMode().getName()) + goods.getStackNum());
					} else {
						goodsMap.put(goods.getGoodsMode().getName(), goods.getStackNum());
					}
					alter += goods.getGoodsMode().getNpcRecover() * coff;// 计算要的增加经验值
					playerBoxs.remove(goods.getStoragePlace());
					equipNum++;

					// sb.append(goods.getGoodsMode().getName()).append('*').append(goods.getStackNum()).append(',');
				}

			}
		} else {
			return null;
		}

		// 使用材料
		Iterator<Entry<String, Integer>> iterator = goodsMap.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, Integer> entry = iterator.next();
			if (sb.length() > 0) {
				sb.append(',').append(entry.getKey()).append('*').append(entry.getValue());
			} else {
				sb.append(entry.getKey()).append('*').append(entry.getValue());
			}
		}

		if (alter > 0) {
			pet.alterExp(alter);
			pet.commitSync();
			if (sb.length() >= 400) {
				sb.delete(400, sb.length());// 容错处理,清理掉400后的长度
			}

			LogServer.recordLog(player, ConstantsLog.player, 30012, pet.getName(), pet.getId(), pet.getMode().getName(), goodsName, goodsId > 0 ? 1 : 0,
					equipNum, alter, sb.toString());
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pet", pet.toVO());

		return ResponseMessage.getSuccMessage(map);
	}
	
	/**
	 * 宠物极速喂养
	 * 
	 * @param session
	 * @param petId
	 * @param type 0普通 1高级 2超级
	 * @return
	 */
	public ResponseMessage fastFeed(Session session, long petId, int type) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Pet pet = player.getDataInfo().getPet(petId);
		if(pet == null) {
			return null;
		} else if (pet.getLevel() >= player.getLevel()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pet.feed.level"));
		}
		if (pet.getLevel() < ConstantsLevel.lv60PetFastFeed) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pet.fastfeed.level", ConstantsLevel.lv60PetFastFeed));
		}
		boolean useGold = type > 0 ? true : false;
		
		if (!useGold && player.getAsset() < ConstantsModel.petFastFeed[type][1]) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.asset"));
		}
		
		if (useGold && player.getGoldAll() < ConstantsModel.petFastFeed[type][1]) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		}
		
		int exp = 0;
		boolean smallCrit = false;
		boolean bigCrit = false;
		boolean expDouble = false;
		int sCTimes = 0;
		int bCTimes = 0;
		if (type == 0) {
			exp = ConstantsModel.petFastFeedExp * ConstantsModel.petFastFeed[type][0];
		} else if (type == 1) {
			for (int i = 0; i < ConstantsModel.petFastFeed[type][0]; i++) {
				smallCrit = NumberProcesser.isWinning(ConstantsModel.petFastFeedCritRate[0]);
				bigCrit = NumberProcesser.isWinning(ConstantsModel.petFastFeedCritRate[1]);
				if (smallCrit) {
					exp += ConstantsModel.petFastFeedExp * 2;
					sCTimes++;
				} else if (bigCrit) {
					exp += ConstantsModel.petFastFeedExp * 5;
					bCTimes++;
				} else {
					exp += ConstantsModel.petFastFeedExp;
				}
			}
		} else if (type == 2) {
			
			//int pff = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.pff);
			//pff++;
			//player.getDataInfo().getEveryDay().intDataSet(ConstantsDayIntKey.pff, pff);
			//expDouble = pff <= 5;
	
			for (int i = 0; i < ConstantsModel.petFastFeed[type][0]; i++) {
				bigCrit = NumberProcesser.isWinning(ConstantsModel.petFastFeedCritRate[2]);
				if (bigCrit) {
					exp += ConstantsModel.petFastFeedExp * 5;
					bCTimes++;
				} else {
					exp += ConstantsModel.petFastFeedExp;
				}
			}
			if (expDouble) {
				//exp *= 2;
			}
		}
		if (useGold) {
			player.alterGoldAll(-ConstantsModel.petFastFeed[type][1]);
			LogServer.costEventLog(session.getUid(), ConstantsModel.petFastFeed[type][1], ConstantsCost.petFastFeed);
		} else {
			player.alterAsset(-ConstantsModel.petFastFeed[type][1]);
		}
		player.commitSync();
		pet.alterExp(exp);
		pet.commitSync();
		LogServer.recordLog(player, ConstantsLog.player, 30028, pet.getName(), ConstantsModel.petFastFeed[type][0], pet.getId(), pet.getMode().getName(), useGold ? ConstantsModel.petFastFeed[type][1] : 0, useGold ? 0 : ConstantsModel.petFastFeed[type][1], exp);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sCTimes", sCTimes);
		map.put("bCTimes", bCTimes);
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		map.put("asset", player.getAsset());
		map.put("exp",exp);
		map.put("pet", pet.toVO());
		map.put("type", type);
		map.put("expDouble", expDouble);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 培养宠物
	 * 
	 * @param session
	 * @param type
	 * @return
	 */
	public ResponseMessage train(Session session, long id, int goodsId) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Pet pet = player.getDataInfo().getPet(id);
		if (pet == null) {
			return null;
		}
		GoodsMode goodsMode = Context.getGoodsServer().getModeById(goodsId);
		if (goodsMode.getAppId() != 113) {
			return null;
		}
		if (!player.getPlayerBoxs().isHaveGoods(goodsId)) {
			return null;
		}
		int[] growthMax = { 0, 200, 300, 400 };
		if (pet.getGrowth() >= growthMax[pet.getStar()]) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pet.train.level"));
		} else if (goodsMode.getValueB() > 100) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.sys"));
		}
		player.getPlayerBoxs().costGoods(goodsId, 1);
		synchronized (pet) {
			int growth = pet.getGrowth() + goodsMode.getValueB();
			growth = growth > growthMax[pet.getStar()] ? growthMax[pet.getStar()] : growth;
			pet.setGrowth(growth);
		}
		pet.clacPropertys();
		pet.setHp(pet.getMaxHp());
		pet.setMp(pet.getMaxMp());

		pet.commitSync();
		Context.getPlayerServer().clacScore(player);
		LogServer.recordLog(player, ConstantsLog.player, 30013, pet.getName(), pet.getId(), pet.getMode().getName(), goodsMode.getGoodsId(),
				goodsMode.getValueB() / 100f, pet.getGrowth() / 100f, goodsMode.getName());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pet", pet.toVO());
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 进化宠物
	 * 
	 * @param session
	 * @param id
	 * @return
	 */
	public ResponseMessage star(Session session, long id) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Pet pet = player.getDataInfo().getPet(id);
		if (pet == null) {
			return null;
		}
		if (pet.getStar() >= 3) {
			return null;
		}
		int goodsId = GoodsEffectConfig.petStarGoodsId;
		GoodsMode goodsMode = Context.getGoodsServer().getModeById(goodsId);
		if (!player.getPlayerBoxs().isHaveGoods(goodsId)) {
			return ResponseMessage.getSuccMessage(false);
		}
		player.getPlayerBoxs().costGoods(goodsId, 1);

		boolean isNoName = pet.getName().equals(pet.getMode().getName());
		String oldModeName = pet.getMode().getName();
		synchronized (pet) {
			int nextModeId = pet.getMode().getNextModeId();
			if (nextModeId == 0) {
				return null;
			}
			pet.setStar(pet.getStar() + 1);
			pet.setModeId(nextModeId);
		}
		if (isNoName) {
			pet.setName(pet.getMode().getName());
		}

		pet.clacPropertys();
		pet.setHp(pet.getMaxHp());
		pet.setMp(pet.getMaxMp());
		pet.commitSync();

		Context.getPlayerServer().clacScore(player);
		LogServer.recordLog(player, ConstantsLog.player, 30014, pet.getName(), pet.getId(), oldModeName, goodsMode.getName(), pet.getStar());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pet", pet.toVO());

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 悟性 修炼 管理
	 * 
	 * @param session
	 * @param id
	 * @return
	 */
	public ResponseMessage perception(Session session, long id) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Pet pet = player.getDataInfo().getPet(id);
		if (pet == null) {
			return null;
		}
		
		if (pet.getSpirit() < 4 && pet.getPerception() <= 0) {//灵性5级后才开放悟性
			return null;
		}

		if (pet.getPerception() >= 10) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pet.per.times"));
		}
		int costGold = ConstantsModel.petPreGold[pet.getPerception()];
		if (player.getGoldAll() < costGold) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		}

		player.alterGoldAll(-costGold);
		player.commitSync();
		LogServer.costEventLog(player.getPlayerId(), costGold, ConstantsCost.petPerception);

		pet.setPerception(pet.getPerception() + 1);
		pet.clacPropertys();
		pet.commitSync();

		pet.setHp(pet.getMaxHp());
		pet.setMp(pet.getMaxMp());

		Context.getPlayerServer().clacScore(player);
		float add = ConstantsModel.petPreAdd[pet.getPerception() - 1] / 10f;
		LogServer.recordLog(player, ConstantsLog.player, 30015, pet.getName(), pet.getId(), pet.getMode().getName(), costGold, pet.getPerception(), add);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		map.put("pet", pet.toVO());

		return ResponseMessage.getSuccMessage(map);
	}
	
	/**
	 * 宠物灵性点化
	 * 
	 * @param session
	 * @param petId
	 * @param type
	 * @return
	 */
	public ResponseMessage spirit(Session session, long petId) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Pet pet = player.getDataInfo().getPet(petId);
		if (pet == null) {
			return null;
		}
		int level = pet.getSpirit();
		if (level >= ConstantsModel.petSpiritMax) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pet.spirit.times"));
		}
		int costGold = ConstantsModel.petSpiritCost[level];
		int costNum = costGold / 5;
		int havaNum = player.getPlayerBoxs().getStackNum(GoodsEffectConfig.spiritGoodsId);
		costNum = costNum > havaNum ? havaNum : costNum;
		costGold = costGold - costNum * 5;
		if (costGold > 0 && player.getGoldAll() < costGold) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		}
		
		boolean suc = NumberProcesser.isWinning(ConstantsModel.petSpiritUpRate[level]);
		if(suc) {
			level++;
		} else {
			level -= ConstantsModel.petSpiritDownLv[level];
		}
		if(level != pet.getSpirit()) {//灵性等级变化
			pet.setSpirit(level);
			pet.clacPropertys();
			pet.commitSync();
	
			pet.setHp(pet.getMaxHp());
			pet.setMp(pet.getMaxMp());
//			int spiritMax = player.getDataInfo().intDataGet(ConstantsIntKey.smax);
//			if (spiritMax < level) {
//				//player.getDataInfo().intDataSet(ConstantsIntKey.smax, level);
//				//player.getDataInfo().commitSync();
//			}
		}
		if (costNum > 0) {
			player.getPlayerBoxs().costGoods(GoodsEffectConfig.spiritGoodsId, costNum);
		} 
		if (costGold > 0){
			player.alterGoldAll(-costGold);
			LogServer.costEventLog(player.getPlayerId(), costGold, ConstantsCost.petSpirit);
		}
		player.commitSync();
		
		float add = ConstantsModel.petSpiritAdd[pet.getSpirit() - 1] / 10f;
		GoodsMode goodsMode = Context.getGoodsServer().getModeById(GoodsEffectConfig.spiritGoodsId);
		LogServer.recordLog(player, ConstantsLog.player, 30029, pet.getName(), pet.getId(), pet.getMode().getName(), costGold, goodsMode.getName(), costNum, level, add);

		Context.getPlayerServer().clacScore(player);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pet", pet.toVO());
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		map.put("suc", suc);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 技能相关
	 * 
	 * @param session
	 * @param id
	 * @return
	 */
	public ResponseMessage study(Session session, long id, int bookId, int targetId) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Pet pet = player.getDataInfo().getPet(id);
		if (pet == null) {
			return null;
		}
		GoodsMode goodsMode = Context.getGoodsServer().getModeById(bookId);
		if (goodsMode == null || goodsMode.getAppId() != 114) {
			return null;
		}
		if (player.getPlayerBoxs().getStackNum(bookId) <= 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("skill.study.nobook", goodsMode.getName()));
		}
		int skillId = goodsMode.getValueA();
		SkillMode currentMode = Context.getSkillServer().getSkillMode(skillId);
		if (currentMode == null) {
			return null;
		}
		int maxSize = ConstantsModel.petSkillGirdFree;
		if (pet.getSkillGird() >= ConstantsModel.petSkillExpMax) {
			maxSize++;
		}
		if (targetId == 0 && pet.getSkillIds() != null && pet.getSkillIds().length >= maxSize) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pet.study.errnum", maxSize));
		}
		int targetIndex = -1;
		String oldName = null;
		int oldLevel = 0;
		for (int i = 0; i < pet.getSkillIds().length; i++) {
			int eid = pet.getSkillIds()[i];
			SkillMode skillMode = Context.getSkillServer().getSkillMode(eid);
			if (skillMode == null) {
				continue;
			}
			if (skillMode.getSkillLibId() == currentMode.getSkillLibId()) {
				if (skillMode.getLevel() >= currentMode.getLevel()) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("pet.study.errlvel"));
				} else if (targetId != skillMode.getId()) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
				}
				oldName = skillMode.getName();
				oldLevel = skillMode.getLevel();
			}
			if (targetId > 0 && skillMode.getId() == targetId) {
				targetIndex = i;
				oldName = skillMode.getName();
				oldLevel = skillMode.getLevel();
			}
		}
		if (targetIndex >= 0) {
			pet.getSkillIds()[targetIndex] = skillId;
		} else if (targetId > 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		} else {
			int[] ids = pet.getSkillIds();
			int newLength = ids.length + 1;
			ids = Arrays.copyOf(ids, newLength);
			ids[newLength - 1] = currentMode.getId();
			pet.setSkillIds(ids);
		}
		pet.clacPropertys();
		pet.commitSync();
		pet.setHp(pet.getMaxHp());
		pet.setMp(pet.getMaxMp());
		player.getPlayerBoxs().costGoods(bookId, 1);

		Context.getPlayerServer().clacScore(player);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pet", pet.toVO());

		LogServer.recordLog(player, ConstantsLog.player, 30016, pet.getName(), pet.getId(), pet.getMode().getName(), currentMode.getName(),
				currentMode.getLevel(), oldName, oldLevel, currentMode.getLevel(), oldLevel);

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 开放技能格子
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage skillGirdOpen(Session session, long id, boolean useGold) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Pet pet = player.getDataInfo().getPet(id);
		if (pet == null) {
			return null;
		}
		if (pet.getSkillGird() >= ConstantsModel.petSkillExpMax) {
			return null;
		}
		if (useGold) {
			if (player.getGoldAll() < ConstantsModel.petSkillOpenGold) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
			}
		} else {
			if (player.getAsset() < ConstantsModel.petskillOpenAsset) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.asset"));
			}
		}

		boolean suc = false, bigCrit = false;
		int exp = 0;
		int costGold = 0, costAsset = 0;
		if (useGold) {
			suc = true;
			bigCrit = NumberProcesser.isWinning(10);
			exp = bigCrit ? 40 : 4;
			costGold = ConstantsModel.petSkillOpenGold;
			player.alterGoldAll(-costGold);
			LogServer.costEventLog(session.getUid(), costGold, ConstantsCost.petSkillOpen);
		} else {
			suc = NumberProcesser.isWinning(20);
			exp = suc ? 2 : 0;
			costAsset = ConstantsModel.petskillOpenAsset;
			player.alterAsset(-costAsset);
		}
		player.commitSync();

		if (exp > 0) {
			pet.alterSkillGird(exp);
			pet.commitSync();
		}
		LogServer.recordLog(player, ConstantsLog.player, 30017, pet.getName(), pet.getId(), costGold, costAsset, exp, pet.getSkillGird());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("asset", player.getAsset());
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		map.put("skillExp", exp);
		map.put("suc", suc);
		map.put("bigCrit", bigCrit);
		map.put("skillGirld", pet.getSkillGird());
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 使用元宝开启兽魂格子
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage huntGirdOpen(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int huntGird = player.getDataInfo().intDataGet(ConstantsIntKey.huntGird);
		if (huntGird >= ConstantsModel.pethuntGirdFree) {
			return null;
		}
		huntGird++;
		int costGold = (huntGird) * 2;
		if (player.getGoldAll() < costGold) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		}
		player.alterGoldAll(-costGold);
		player.commitSync();
		player.getDataInfo().intDataSet(ConstantsIntKey.huntGird, huntGird);
		player.getDataInfo().commitSync();

		LogServer.costEventLog(session.getUid(), costGold, ConstantsCost.petHuntOpen);
		LogServer.recordLog(player, ConstantsLog.player, 30018, costGold, huntGird);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		map.put("huntGird", huntGird + ConstantsModel.pethuntGirdFree);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 显示宠物命格
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage huntLifeShow(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Map<Integer, Integer> huntMap = player.getDataInfo().huntAll();
		List<PetSoulVO> souls = new ArrayList<PetSoulVO>();
		if (huntMap != null && !huntMap.isEmpty()) {
			for (Map.Entry<Integer, Integer> entry : huntMap.entrySet()) {
				PetSoul petSoul = Context.getPetServer().getSoul(entry.getValue());
				if (petSoul == null) {
					continue;
				}
				int exp = player.getDataInfo().huntExpGet(entry.getKey());
				souls.add(new PetSoulVO(entry.getKey(), exp, petSoul));
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		if (player.getDataInfo().intDataGet(ConstantsIntKey.huntGird) > ConstantsModel.pethuntGirdFree) {
			player.getDataInfo().intDataSet(ConstantsIntKey.huntGird, ConstantsModel.pethuntGirdFree);
		}

		map.put("souls", souls);
		map.put("huntGird", player.getDataInfo().intDataGet(ConstantsIntKey.huntGird) + ConstantsModel.pethuntGirdFree);
		map.put("huntFree", ConstantsModel.petHuntPlayFree - player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.hFree));
		map.put("huntNpc", player.getDataInfo().intDataGet(ConstantsIntKey.huntNpc));
		map.put("huntExt", player.getDataInfo().intDataGet(ConstantsIntKey.huntExt));

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 召唤兽魂
	 * 
	 * @param session
	 * @param type
	 * @return
	 */
	public ResponseMessage huntPlay(Session session, int type) {
		if (type < 0 || type >= ConstantsModel.petHuntAsset.length) {
			return null;
		}
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int hFree = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.hFree);
		int huntNpc = player.getDataInfo().intDataGet(ConstantsIntKey.huntNpc);
		if (type > 0 && (huntNpc & (1 << (type - 1))) <= 0) {
			return null;
		}
		if (player.getDataInfo().intDataGet(ConstantsIntKey.huntGird) + ConstantsModel.pethuntGirdFree <= player.getDataInfo().huntSize()) {
			return null;
		}
		boolean useAsset = hFree >= ConstantsModel.petHuntPlayFree;
		hFree++;

		if (useAsset && player.getAsset() < ConstantsModel.petHuntAsset[type]) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.asset"));
		}
		int color = NumberProcesser.rateIndex(ConstantsModel.petHuntRate[type]);
		int huntType = 0, level = 1;
		if (color == 0) {
			huntType = NumberProcesser.mtRand(21, 27);
		} else {
			huntType = NumberProcesser.mtRand(8);
			if (color == 5) {
				huntType = NumberProcesser.isWinning(50)? 2 : 8;
			}
		}
		boolean activation = NumberProcesser.isWinning(ConstantsModel.petHuntNext[type]);
		PetSoul petSoul = Context.getPetServer().getSoul(huntType, color, level);
		if (petSoul == null) {
			return null;
		}
		int costAsset = 0;
		if (useAsset) {
			costAsset = ConstantsModel.petHuntAsset[type];
			player.alterAsset(-costAsset);
		} else {
			player.getDataInfo().getEveryDay().intDataSet(ConstantsDayIntKey.hFree, hFree);
		}
		if (type > 0) {
			huntNpc = huntNpc & ~(1 << (type - 1));
		}
		if (activation) {
			huntNpc = huntNpc | (1 << type);

		} else if (huntNpc == 0 && type > 0) {
			player.getDataInfo().intDataRemove(ConstantsIntKey.huntNpc);// 清理key
		}
		player.getDataInfo().intDataSet(ConstantsIntKey.huntNpc, huntNpc);
		int indexId = player.getDataInfo().huntAdd(petSoul.getId());
		boolean reciveExt = NumberProcesser.isWinning(ConstantsModel.petHuntExtRate[type]);
		int huntExt = player.getDataInfo().intDataGet(ConstantsIntKey.huntExt);
		if (reciveExt) {
			huntExt++;
			player.getDataInfo().intDataSet(ConstantsIntKey.huntExt, huntExt);
			ChatMain.systemMessageDelay(LanguageLib.get("pet.hunt.got1", player.getPlayerName()), 5);
		}

		//如果是免费征魂
		if (!useAsset) {
			//加入到每日奖励
			player.getDataInfo().getEveryDay().finishDailyItem(ConstantsDailyItem.getSoulFreeOnceItem);
		}
		
		player.getDataInfo().commitSync();
		player.commitSync();

		LogServer.recordLog(player, ConstantsLog.player, 30019, costAsset, type, petSoul.getName(), petSoul.getColor(), activation,huntExt);
		if (petSoul.getColor() >= 3) {
			ChatMain.systemMessage(LanguageLib.get("pet.hunt.got2", player.getPlayerName(), LangUtil.makeHtml(petSoul.getColor(), petSoul.getName())));
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("asset", player.getAsset());
		map.put("soul", new PetSoulVO(indexId, 0, petSoul));
		map.put("huntNpc", huntNpc);
		map.put("huntFree", ConstantsModel.petHuntPlayFree - hFree);
		map.put("reciveExt", reciveExt);
		map.put("huntExt", huntExt);

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 一键猎命
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage huntPlayAuto(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int huntNpc = player.getDataInfo().intDataGet(ConstantsIntKey.huntNpc);
		int hFree = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.hFree);
		boolean useAsset = hFree >= ConstantsModel.petHuntPlayFree;
		int huntHaveSize = player.getDataInfo().huntSize();
		int huntMax = player.getDataInfo().intDataGet(ConstantsIntKey.huntGird) + ConstantsModel.pethuntGirdFree;
		if (huntMax <= huntHaveSize) {
			return null;
		}
		int costAsset = 0;
		int currentNpc = 0;
		if (huntNpc > 0) {
			for (int i = 0; i < ConstantsModel.petHuntAsset.length; i++) {
				if ((huntNpc & (1 << i)) > 0) {
					currentNpc = i + 1;
					break;
				}
			}
		}
		int currentNum = 0;
		int tmpAsset = 0;
		int huntExt = player.getDataInfo().intDataGet(ConstantsIntKey.huntExt);
		int reciveExt = 0;

		StringBuilder sb = new StringBuilder();
		while (currentNum < huntMax - huntHaveSize) {
			if (currentNpc >= ConstantsModel.petHuntAsset.length) {
				LogUtil.getMain().error("err npc " + currentNpc);
				currentNpc = 0;
			}
			if (hFree < ConstantsModel.petHuntPlayFree) {
				tmpAsset = 0;
				hFree++;
			} else {
				tmpAsset = ConstantsModel.petHuntAsset[currentNpc];
			}
			if (tmpAsset + costAsset > player.getAsset()) {
				break;
			}
			currentNum++;
			int color = NumberProcesser.rateIndex(ConstantsModel.petHuntRate[currentNpc]);
			int huntType = 0, level = 1;
			if (color == 0) {
				huntType = NumberProcesser.mtRand(21, 27);
			} else {
				huntType = NumberProcesser.mtRand(8);
				if (color == 5) {
					huntType = NumberProcesser.isWinning(50)? 2 : 8;
				}
			}
			PetSoul petSoul = Context.getPetServer().getSoul(huntType, color, level);
			if (petSoul == null) {
				LogUtil.getMain().error("soul err ");
				continue;
			}
			sb.append(petSoul.getName()).append(petSoul.getColor()).append(',');

			player.getDataInfo().huntAdd(petSoul.getId());// 增加兽魂到包裹

			costAsset += tmpAsset;// 记录消耗的银两
			boolean activation = NumberProcesser.isWinning(ConstantsModel.petHuntNext[currentNpc]);
			if (currentNpc != 0) {
				huntNpc = huntNpc & ~(1 << (currentNpc - 1));
				if (NumberProcesser.isWinning(ConstantsModel.petHuntExtRate[currentNpc])) {
					reciveExt++;
				}
			}
			if (activation) {
				currentNpc++;
			} else {
				currentNpc = 0;
			}
			if (petSoul.getColor() >= 3) {
				ChatMain.systemMessageDelay(LanguageLib.get("pet.hunt.got2", player.getPlayerName(), LangUtil.makeHtml(petSoul.getColor(), petSoul.getName())),
						5);
			}
		}
		if (costAsset > 0) {
			player.alterAsset(-costAsset);
		}
		if (currentNpc > 0) {
			huntNpc = huntNpc & (1 << (currentNpc - 1));
		}
		if (reciveExt > 0) {
			huntExt += reciveExt;
			ChatMain.systemMessageDelay(LanguageLib.get("pet.hunt.got1", player.getPlayerName()), 5);
			player.getDataInfo().intDataSet(ConstantsIntKey.huntExt, huntExt);
		}
		if (huntNpc > 0) {
			player.getDataInfo().intDataSet(ConstantsIntKey.huntNpc, huntNpc);
		} else {
			player.getDataInfo().intDataRemove(ConstantsIntKey.huntNpc);
		}
		player.getDataInfo().getEveryDay().intDataSet(ConstantsDayIntKey.hFree, hFree);
		player.commitSync();
		//如果是免费征魂
		if (!useAsset) {
			//加入到每日奖励
			player.getDataInfo().getEveryDay().finishDailyItem(ConstantsDailyItem.getSoulFreeOnceItem);
		}
		player.getDataInfo().commitSync();

		LogServer.recordLog(player, ConstantsLog.player, 30020, costAsset, currentNum, sb.toString(),huntExt);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("currentNum", currentNum);
		map.put("costAsset", costAsset);
		map.put("asset", player.getAsset());
		map.put("huntExt", huntExt);
		map.put("reciveExt", reciveExt);

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 兽魂合成
	 * 
	 * @param session
	 * @param sourceId
	 * @param targetId
	 * @param autoAll
	 * @return
	 */
	public ResponseMessage huntMerge(Session session, int sourceId, int targetId) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int sId = player.getDataInfo().huntGet(sourceId);
		int tId = player.getDataInfo().huntGet(targetId);
		if (sId == 0 || sourceId == targetId) {
			return null;
		}
		int huntMax = player.getDataInfo().intDataGet(ConstantsIntKey.huntGird) + ConstantsModel.pethuntGirdFree;
		if (targetId > huntMax) {
			return null;
		}
		PetSoul sourceSoul = Context.getPetServer().getSoul(sId);
		if (tId == 0) {
			int expCurrent = player.getDataInfo().huntExpGet(sourceId);
			player.getDataInfo().huntRemove(sourceId);
			player.getDataInfo().huntPut(targetId, sourceSoul.getId());
			player.getDataInfo().huntExpSet(targetId, expCurrent);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("soul", new PetSoulVO(targetId, expCurrent, sourceSoul));
			map.put("delSoul", sourceId);
			return ResponseMessage.getSuccMessage(map);
		}

		PetSoul targetSoul = Context.getPetServer().getSoul(tId);

		if (sourceSoul == null || targetSoul == null) {
			LogUtil.getSysErr().error("soul null " + player.getAccountName());
			return null;
		}
		if (sourceSoul.getColor() == 0 || targetSoul.getColor() == 0) {
			return null;
		} else if (targetSoul.getUpgradeExp() == 0 && sourceSoul.getUpgradeExp() == 0) {
			return null;// 不可升级
		}
		PetSoulOrder sourceOrder = new PetSoulOrder(sourceId, sourceSoul, player.getDataInfo().huntExpGet(sourceId));
		PetSoulOrder targetOrder = new PetSoulOrder(targetId, targetSoul, player.getDataInfo().huntExpGet(targetId));
		PetSoulOrder mainSoul = sourceOrder;
		PetSoulOrder otherSoul = targetOrder;
		if (sourceOrder.compareTo(targetOrder) > 0) {
			mainSoul = targetOrder;
			otherSoul = sourceOrder;
		}
		if (mainSoul.getPetSoul().getUpgradeExp() == 0) {
			return null;
		}
		PetSoul mainPetSoul = mainSoul.getPetSoul();
		int oldLevel = mainPetSoul.getLevel();
		int receiveExp = otherSoul.getPetSoul().getEngulfExp() + otherSoul.getExp();

		int expCurrent = player.getDataInfo().huntExpGet(mainSoul.getIndexId()) + receiveExp;
		player.getDataInfo().huntRemove(sourceId);// 把低级的消耗掉
		player.getDataInfo().huntRemove(targetId);// 把2个都消耗掉

		while (expCurrent >= mainPetSoul.getUpgradeExp() && mainPetSoul.getUpgradeExp() > 0) {
			expCurrent -= mainPetSoul.getUpgradeExp();
			mainPetSoul = Context.getPetServer().getSoul(mainPetSoul.getType(), mainPetSoul.getColor(), mainPetSoul.getLevel() + 1);
		}
		player.getDataInfo().huntPut(targetId, mainPetSoul.getId());
		if (mainPetSoul.getUpgradeExp() == 0) {
			expCurrent = 0;// 升级到满级后,无经验
		}
		player.getDataInfo().huntExpSet(targetId, expCurrent);
		player.getDataInfo().commitSync();

		LogServer.recordLog(player, ConstantsLog.player, 30021, sourceSoul.getName(), sourceSoul.getColor(), sourceSoul.getLevel(), sourceOrder.getExp(),
				targetSoul.getName(), targetSoul.getColor(), targetSoul.getLevel(), targetOrder.getExp(), mainPetSoul.getName(), mainPetSoul.getColor(),
				mainPetSoul.getLevel(), expCurrent);

		if (oldLevel != mainPetSoul.getLevel() && mainPetSoul.getLevel() >= 4) {
			ChatMain.systemMessage(LanguageLib.get("pet.hunt.level", LangUtil.makeNameLink(player), mainPetSoul.getName(), mainPetSoul.getLevel()));
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("soul", new PetSoulVO(targetId, expCurrent, mainPetSoul));
		map.put("delSoul", sourceId);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 一键合并
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage huntMergeAuto(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Map<Integer, Integer> huntMap = player.getDataInfo().huntAll();
		if (huntMap == null || huntMap.isEmpty()) {
			return null;
		}
		List<PetSoulOrder> soulOrders = new ArrayList<PetSoulOrder>();

		for (Map.Entry<Integer, Integer> entry : huntMap.entrySet()) {
			PetSoul petSoul = Context.getPetServer().getSoul(entry.getValue());
			if (petSoul == null || petSoul.getColor() == 0 || (petSoul.getUpgradeExp() == 0 && petSoul.getColor() == 4)) {
				continue;
			}
			int exp = player.getDataInfo().huntExpGet(entry.getKey());
			soulOrders.add(new PetSoulOrder(entry.getKey(), petSoul, exp));
		}
		if (soulOrders == null || soulOrders.size() <= 1) {
			return null;
		}
		Collections.sort(soulOrders);
		PetSoulOrder mainSoulOrder = null;
		Iterator<PetSoulOrder> it = soulOrders.iterator();

		while (it.hasNext()) {
			PetSoulOrder e = (PetSoulOrder) it.next();
			if (e.getPetSoul().getUpgradeExp() > 0) {
				mainSoulOrder = e;
				break;
			} else {
				it.remove();
			}
		}

		if (mainSoulOrder == null || mainSoulOrder.getPetSoul().getUpgradeExp() == 0) {
			return null;
		}
		PetSoul mainSoul = mainSoulOrder.getPetSoul();
		soulOrders.remove(mainSoul);// 把主清理掉

		int mainExp = mainSoulOrder.getExp();
		int mainLevel = mainSoul.getLevel();
		int delSoul = 0;
		int expReviveAll = 0;
		StringBuilder sb = new StringBuilder();
		int allSize = soulOrders.size();
		for (int i = allSize - 1; i >= 0; i--) {
			PetSoulOrder e = soulOrders.get(i);
			if (e.getIndexId() == mainSoulOrder.getIndexId()) {
				continue;
			}
			int expRevive = e.getPetSoul().getEngulfExp() + e.getExp();
			mainExp += expRevive;
			expReviveAll += expRevive;
			player.getDataInfo().huntRemove(e.getIndexId());// 移除老的
			delSoul++;
			sb.append(e.getPetSoul().getName()).append(e.getPetSoul().getColor()).append('-').append(e.getPetSoul().getLevel()).append(';');
			while (mainExp >= mainSoul.getUpgradeExp() && mainSoul.getUpgradeExp() > 0) {
				mainExp -= mainSoul.getUpgradeExp();
				mainSoul = Context.getPetServer().getSoul(mainSoul.getType(), mainSoul.getColor(), mainSoul.getLevel() + 1);
			}
			if (mainSoul.getUpgradeExp() == 0) {// 不能再升级
				mainExp = 0;
			}
		}

		if (mainLevel != mainSoul.getLevel()) {
			player.getDataInfo().huntPut(mainSoulOrder.getIndexId(), mainSoul.getId());
			if (mainSoul.getLevel() >= 4) {
				ChatMain.systemMessage(LanguageLib.get("pet.hunt.level", LangUtil.makeNameLink(player), mainSoul.getName(), mainSoul.getLevel()));
			}
		}
		player.getDataInfo().huntExpSet(mainSoulOrder.getIndexId(), mainExp);
		player.getDataInfo().commitSync();
		LogServer.recordLog(player, ConstantsLog.player, 30022, delSoul, mainSoul.getName(), mainSoul.getColor(), mainSoul.getLevel(), mainExp, sb.toString());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("expReviveAll", expReviveAll);
		map.put("soul", new PetSoulVO(mainSoulOrder.getIndexId(), mainExp, mainSoul));
		map.put("delSoul", delSoul);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 出售兽魂
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage huntSale(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int saleNum = 0;
		int receiveAsset = 0;
		Map<Integer, Integer> huntMap = player.getDataInfo().huntAll();

		if (huntMap != null && !huntMap.isEmpty()) {
			Iterator<Integer> it = huntMap.keySet().iterator();
			while (it.hasNext()) {
				int key = it.next();
				int value = huntMap.get(key);
				PetSoul petSoul = Context.getPetServer().getSoul(value);
				if (petSoul != null && petSoul.getColor() != 0) {
					continue;
				}
				if (petSoul != null) {
					saleNum++;
					receiveAsset += petSoul.getAsset();
				}
				it.remove();
			}
		}
		player.alterAsset(receiveAsset);
		player.commitSync();
		player.getDataInfo().commitSync();
		LogServer.recordLog(player, ConstantsLog.player, 30023, receiveAsset);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("saleNum", saleNum);
		map.put("receiveAsset", receiveAsset);
		map.put("asset", player.getAsset());
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 命格安装
	 * 
	 * @param session
	 * @param id
	 * @param sourceId
	 * @param targetId
	 * @return
	 */
	public ResponseMessage huntInstall(Session session, long id, int sourceId, int targetId) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Pet pet = player.getDataInfo().getPet(id);
		if (pet == null) {
			return null;
		}
		int girdId = NumberProcesser.floor(pet.getLevel() - 40, 5);
		if (targetId == 0 || targetId > girdId || targetId > 8) {
			return null;
		}
		int sId = player.getDataInfo().huntGet(sourceId);
		PetSoul sourceSoul = Context.getPetServer().getSoul(sId);
		if (sourceSoul == null || sourceSoul.getColor() == 0) {
			return null;
		}
		int sourceExp = player.getDataInfo().huntExpGet(sourceId);
		PetSoulOrder sourceOrder = new PetSoulOrder(0, sourceSoul, sourceExp);

		Soul targetHunt = pet.getHuntsMap().get(targetId);
		boolean isSource = true;
		PetSoulOrder targetOrder = null;
		boolean checkOther = true;
		if (targetHunt != null) {
			PetSoul targetSoul = Context.getPetServer().getSoul(targetHunt.getId());
			if (sourceSoul.getColor() == targetSoul.getColor() && sourceSoul.getUpgradeExp() == 0 && targetSoul.getUpgradeExp() == 0) {
				return null;// 同等级不可升级不可吞噬
			}
			targetOrder = new PetSoulOrder(0, targetSoul, targetHunt.getExp());
			if (sourceOrder.compareTo(targetOrder) <= 0) {

			} else {
				isSource = false;
				checkOther = false;
			}
		}
		if (checkOther) {
			if (!pet.getHuntsMap().isEmpty()) {
				for (Map.Entry<Integer, Soul> entry : pet.getHuntsMap().entrySet()) {
					PetSoul otherSoul = Context.getPetServer().getSoul(entry.getValue().getId());
					if (otherSoul != null && otherSoul.getType() == sourceSoul.getType() && entry.getKey() != targetId) {
						return ResponseMessage
								.ticpErrMsg(LanguageLib.get("pet.hunt.installother", LangUtil.makeHtml(otherSoul.getColor(), otherSoul.getName())));
					}
				}
			}
		}
		int expRecive = 0;
		PetSoulOrder mainOrder = null;
		if (isSource || targetOrder == null) {
			mainOrder = sourceOrder;
			if (targetOrder != null) {
				expRecive = targetOrder.getPetSoul().getEngulfExp() + targetOrder.getExp();
			}
		} else {
			mainOrder = targetOrder;
			expRecive = sourceOrder.getPetSoul().getEngulfExp() + sourceOrder.getExp();
		}
		PetSoul mainSoul = sourceSoul;
		if (targetOrder != null && mainOrder.getPetSoul().getUpgradeExp() == 0) {
			return null;
		}
		int expCurrent = sourceExp;
		if (targetOrder == null) {
			pet.getHuntsMap().put(targetId, new Soul(sourceSoul.getId(), sourceExp));
		} else {
			expCurrent = mainOrder.getExp() + expRecive;
			mainSoul = mainOrder.getPetSoul();

			while (expCurrent >= mainSoul.getUpgradeExp() && mainSoul.getUpgradeExp() > 0) {
				expCurrent -= mainSoul.getUpgradeExp();
				mainSoul = Context.getPetServer().getSoul(mainSoul.getType(), mainSoul.getColor(), mainSoul.getLevel() + 1);
			}
			if (mainSoul.getUpgradeExp() == 0) {
				expCurrent = 0;
			}
			pet.getHuntsMap().put(targetId, new Soul(mainSoul.getId(), expCurrent));

		}
		pet.clacPropertys();
		pet.commitSync();
		player.getDataInfo().huntRemove(sourceId);
		player.getDataInfo().commitSync();
		Context.getPlayerServer().clacScore(player);
		LogServer.recordLog(player, ConstantsLog.player, 30024, targetId, sourceSoul.getName(), sourceSoul.getColor(), sourceSoul.getLevel(), sourceExp,
				mainSoul.getName(), mainSoul.getColor(), mainSoul.getLevel(), expCurrent, pet.getName(), pet.getId(),targetOrder==null?null:targetOrder.getPetSoul().getName());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("delSoul", sourceOrder.getIndexId());
		map.put("pet", pet.toVO());
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 兽魂还原到格子
	 * 
	 * @param session
	 * @param id
	 * @param sourceId
	 * @param targetId
	 * @return
	 */
	public ResponseMessage huntUnstall(Session session, long id, int sourceId, int targetId) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Pet pet = player.getDataInfo().getPet(id);
		if (pet == null) {
			return null;
		}
		Soul soul = pet.getHuntsMap().get(sourceId);
		if (soul == null) {
			return null;
		}
		int huntMax = player.getDataInfo().intDataGet(ConstantsIntKey.huntGird) + ConstantsModel.pethuntGirdFree;
		if (targetId <= 0 || targetId > huntMax) {
			return null;
		}
		int tId = player.getDataInfo().huntGet(targetId);
		if (tId != 0) {
			return null;
		}
		PetSoul petSoul = Context.getPetServer().getSoul(soul.getId());
		pet.getHuntsMap().remove(sourceId);
		player.getDataInfo().huntPut(targetId, petSoul.getId());
		int exp = soul.getExp();
		if (exp > 0) {
			player.getDataInfo().huntExpSet(targetId, exp);
		}
		pet.clacPropertys();
		pet.fixHpMp();
		pet.commitSync();
		player.getDataInfo().commitSync();

		Context.getPlayerServer().clacScore(player);
		LogServer.recordLog(player, ConstantsLog.player, 30025, sourceId, petSoul.getName(), petSoul.getColor(), petSoul.getLevel(), exp, pet.getName(),
				pet.getId());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pet", pet.toVO());
		map.put("soul", new PetSoulVO(targetId, exp, petSoul));

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 命格升级
	 * 
	 * @param session
	 * @param id
	 * @param sourceId
	 * @param type
	 * @return
	 */
	public ResponseMessage huntUpgrade(Session session, long id, int sourceId, int type) {
		if (type < 0 || type >= ConstantsModel.petHuntUpgrade.length) {
			return null;
		}
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Pet pet = player.getDataInfo().getPet(id);
		if (pet == null) {
			return null;
		}
		Soul soul = pet.getHuntsMap().get(sourceId);
		if (soul == null) {
			return null;
		}
		PetSoul mainSoul = Context.getPetServer().getSoul(soul.getId());
		if (mainSoul.getUpgradeExp() == 0) {
			return null;
		}
		int[] config = ConstantsModel.petHuntUpgrade[type];
		if (player.getGoldAll() < config[0]) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		}
		player.alterGoldAll(-config[0]);// 消耗元宝

		int oldLevel = mainSoul.getLevel();
		boolean bigCrit = NumberProcesser.isWinning(config[2]);
		int exp = bigCrit ? config[1] * 10 : config[1];
		boolean reciveExt = NumberProcesser.isWinning(config[3]);

		int currentExp = exp + soul.getExp();
		while (currentExp >= mainSoul.getUpgradeExp() && mainSoul.getUpgradeExp() != 0) {
			currentExp -= mainSoul.getUpgradeExp();
			mainSoul = Context.getPetServer().getSoul(mainSoul.getType(), mainSoul.getColor(), mainSoul.getLevel() + 1);
		}
		if (mainSoul.getUpgradeExp() == 0) {
			currentExp = 0;
		}
		pet.getHuntsMap().put(sourceId, new Soul(mainSoul.getId(), currentExp));
		pet.clacPropertys();
		pet.commitSync();
		int huntExt = player.getDataInfo().intDataGet(ConstantsIntKey.huntExt);
		if (reciveExt) {
			huntExt++;
			player.getDataInfo().intDataSet(ConstantsIntKey.huntExt, huntExt);
			ChatMain.systemMessageDelay(LanguageLib.get("pet.hunt.got1", player.getPlayerName()), 5);
		}
		player.commitSync();
		player.getDataInfo().commitSync();
		LogServer.costEventLog(session.getUid(), config[0], ConstantsCost.petHuntUpgrade);
		Context.getPlayerServer().clacScore(player);
		LogServer.recordLog(player, ConstantsLog.player, 30026, pet.getName(), pet.getId(), sourceId, config[0], exp, reciveExt, huntExt, mainSoul.getName(),
				mainSoul.getColor(), mainSoul.getLevel(), currentExp);

		if (bigCrit) {
			ChatMain.systemMessage(LanguageLib.get("pet.hunt.crit", LangUtil.makeNameLink(player), pet.getName()));
		}
		if (oldLevel != mainSoul.getLevel() && mainSoul.getLevel() >= 4) {
			ChatMain.systemMessage(LanguageLib.get("pet.hunt.level", LangUtil.makeNameLink(player), mainSoul.getName(), mainSoul.getLevel()));
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pet", pet.toVO());
		map.put("bigCrit", bigCrit);
		map.put("reciveExp", exp);
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		map.put("reciveExt", reciveExt);
		map.put("huntExt", huntExt);

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 兽魂兑换
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage huntExchangeShow(Session session) {
		List<PetSoul> souls = new ArrayList<PetSoul>();
		for (PetSoul e : Context.getPetServer().getSouls()) {
			if (e.getCost() == 0) {
				continue;
			}
			souls.add(e);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("souls", souls);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 命格兑换
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage huntExchange(Session session, int id) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		PetSoul petSoul = Context.getPetServer().getSoul(id);
		if (petSoul == null || petSoul.getCost() <= 0) {
			return null;
		}
		int huntHaveSize = player.getDataInfo().huntSize();
		int huntMax = player.getDataInfo().intDataGet(ConstantsIntKey.huntGird) + ConstantsModel.pethuntGirdFree;
		if (huntMax <= huntHaveSize) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pet.hunt.maxsize"));
		}
		int huntExt = player.getDataInfo().intDataGet(ConstantsIntKey.huntExt);
		if (huntExt < petSoul.getCost()) {
			return null;
		}
		huntExt -= petSoul.getCost();
		player.getDataInfo().intDataSet(ConstantsIntKey.huntExt, huntExt);
		int indexId = player.getDataInfo().huntAdd(petSoul.getId());
		player.getDataInfo().commitSync();
		LogServer.recordLog(player, ConstantsLog.player, 30027, petSoul.getCost(), huntExt, petSoul.getName(), petSoul.getColor());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("soul", new PetSoulVO(indexId, 0, petSoul));
		map.put("huntExt", huntExt);
		return ResponseMessage.getSuccMessage(map);
	}
	
	/**
	 * 显示传承能得到的经验和可升到等级
	 * 
	 * @param session
	 * @param sourceId
	 * @param targetId
	 * @return
	 */
	public ResponseMessage heritageShow(Session session, long sourceId, long targetId) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Pet sourcePet = player.getDataInfo().getPet(sourceId);
		Pet targetPet = player.getDataInfo().getPet(targetId);
		if (sourcePet == null || targetPet == null) {
			return null;
		}
		
		long heritageExp = targetPet.getExp();
		for (int i = 1; i < targetPet.getLevel(); i++) {
			heritageExp += LevelUpgrade.getByLevel(i).getPetExp();
		}
		long allExp = heritageExp + sourcePet.getExp();
		int level = sourcePet.getLevel();
		long expNeed = LevelUpgrade.getByLevel(level).getPetExp();
		while (allExp >= expNeed) {
			allExp -= expNeed;
			level++;
			expNeed = LevelUpgrade.getByLevel(level).getPetExp();
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("exp", heritageExp);
		map.put("level", level);
		return ResponseMessage.getSuccMessage(map);
	}
	
	/**
	 * 宠物传承
	 * 
	 * @param session
	 * @param sourceId 接收宠物id
	 * @param targetId 传出宠物id
	 * @param type 1元宝，2银两
	 * @param herType  	1经验 2悟性 3灵性 4成长
	 * @return
	 */
	public ResponseMessage heritage(Session session, long sourceId, long targetId, int type, int herType) {
		if (type < 1 || type > 2 || herType < 1 || herType > 4) {
			return null;
		}
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Pet sourcePet = player.getDataInfo().getPet(sourceId);
		Pet targetPet = player.getDataInfo().getPet(targetId);
		if (sourcePet == null || targetPet == null) {
			return null;
		}
		
		int cost = 0;
		boolean isCostGold = type == 1;
		
		if(herType == 1) {//经验
			int indexLv = 0;
			for (int i = 0; i < ConstantsModel.petHeritageCost.length; i++) {
				if (targetPet.getLevel() <= ConstantsModel.petHeritageCost[i][0]) {
					indexLv = i;
					break;
				}
			}
			cost = ConstantsModel.petHeritageCost[indexLv][type];
		} else if (herType == 2) {//悟性
			cost = isCostGold ? targetPet.getPerception() * 10 : targetPet.getPerception() * 500000;
		} else if (herType == 3) {//灵性
			cost = isCostGold ? targetPet.getSpirit() * 6 : targetPet.getSpirit() * 300000;
		} else if (herType == 4) {//成长
			cost = isCostGold ? targetPet.getGrowth() * 15 : targetPet.getGrowth() * 750000;
			cost /= 100;
		}
			
		
		if (isCostGold && player.getGoldAll() < cost) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		} else if (!isCostGold && player.getAsset() < cost) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.asset"));
		}
		int sourceBefore = 0;
		int targetBefore = 0;
		int sourceAfter = 0;
		int targetAfter = 0;
		long heritageExp = 0;
		if (herType == 1) {//经验
			if (!targetPet.getHuntsMap().isEmpty() || targetPet.getExp() <= 0) {
				return null;
			}
			heritageExp = targetPet.getExp();
			for (int i = 1; i < targetPet.getLevel(); i++) {
				heritageExp += LevelUpgrade.getByLevel(i).getPetExp();
			}
			sourceBefore = sourcePet.getLevel();
			targetBefore = targetPet.getLevel();
			
			sourcePet.alterExp(heritageExp);
			sourcePet.fixHpMp();
			targetPet.setLevel(1);
			targetPet.setExp(0);
			targetPet.fixHpMp();
			
			sourceAfter = sourcePet.getLevel();
			targetAfter = targetPet.getLevel();
		} else if (herType == 2) {//悟性
			if (targetPet.getPerception() <= sourcePet.getPerception()) {
				return null;
			}
			sourceBefore = sourcePet.getPerception();
			targetBefore = targetPet.getPerception();
			
			sourcePet.setPerception(targetBefore);
			targetPet.setPerception(0);
			
			sourceAfter = sourcePet.getPerception();
			targetAfter = targetPet.getPerception();
		}  else if (herType == 3) {//灵性
			if (targetPet.getSpirit() <= sourcePet.getSpirit()) {
				return null;
			}
			sourceBefore = sourcePet.getSpirit();
			targetBefore = targetPet.getSpirit();
			
			sourcePet.setSpirit(targetBefore);
			targetPet.setSpirit(0);
			
			sourceAfter = sourcePet.getSpirit();
			targetAfter = targetPet.getSpirit();
		} else if (herType == 4) {//成长值
			if (sourcePet.getStar() < targetPet.getStar() || targetPet.getGrowth() <= sourcePet.getGrowth()) {
				return null;
			}
			sourceBefore = sourcePet.getGrowth();
			targetBefore = targetPet.getGrowth();
			
			sourcePet.setGrowth(targetBefore);
			targetPet.setGrowth(sourceBefore);
			
			sourceAfter = sourcePet.getGrowth();
			targetAfter = targetPet.getGrowth();
		}
		sourcePet.clacPropertys();
		sourcePet.commitSync();
		targetPet.clacPropertys();
		targetPet.commitSync();
		
		if (isCostGold) {
			player.alterGoldAll(-cost);
			LogServer.costEventLog(session.getUid(), cost, ConstantsCost.petHeritage);
		} else {
			player.alterAsset(-cost);
		}
		Context.getPlayerServer().clacScore(player);
		player.commitSync();
		
		LogServer.recordLog(player, ConstantsLog.player, 30030, sourcePet.getName(), sourcePet.getId(), sourcePet.getMode().getName(), 
				targetPet.getName(), targetPet.getId(), targetPet.getMode().getName(), herType, sourceBefore, targetBefore, sourceAfter, targetAfter, heritageExp, isCostGold ? cost : 0, isCostGold ? 0 : cost);
		Map<String , Object> map = new HashMap<String, Object>();
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		map.put("asset", player.getAsset());
		map.put("sourcePet", sourcePet.toVO());
		map.put("targetPet", targetPet.toVO());
		return ResponseMessage.getSuccMessage(map);
	}

}
